package com.cimr.service.file.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.cimr.comm.base.BaseDao;
import com.cimr.comm.base.BaseServiceImpl;
import com.cimr.dao.file.UnitFileDao;
import com.cimr.dto.file.FileDto;
import com.cimr.po.file.UnitFile;
import com.cimr.service.file.UnitFileService;
import com.cimr.util.ConfigUtil;
import com.cimr.util.FileUtil;
import com.cimr.util.ImageUtil;
import com.cimr.util.RandomUtil;
import com.xlybase.file.service.FastDFSService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by suhuanzhao on 2017/12/25.
 */
@Service
public class UnitFileServiceImpl extends BaseServiceImpl<UnitFile> implements UnitFileService {

    @Autowired
    private UnitFileDao unitFileDao;

    @Override
    protected BaseDao getDao() {
        return unitFileDao;
    }

    @Override
    public List<FileDto> saveFileTemp(MultipartFile[] mfs, String realPath) {
        //获取文件的缓存路径
        String upath = ConfigUtil.getStringValue("smbdp.tempPath");
        File uploadFilePath = new File(realPath + upath);
        if (!uploadFilePath.exists()) {
            uploadFilePath.mkdirs();
        }
        String minLogoUrl = "";
        List<FileDto> fileDtoList = new ArrayList<FileDto>();
        FileDto fileDto = null;
        try {
            //循环每一张上传的图片
            for (MultipartFile mf : mfs) {
                fileDto = new FileDto();
                //获取文件的原文件名
                String fname = mf.getOriginalFilename();
                System.out.println("类型:" + mf.getContentType());
                //缓存文件的原文件名
                String realName = fname;
                //文件格式
                String ext;
                if (fname.lastIndexOf(".") > 0) {
                    ext = fname.substring(fname.lastIndexOf(".") + 1, fname.length());
                } else {
                    ext = "";
                }
                //生成服务器上的文件名称
                fname = System.currentTimeMillis() + RandomUtil.random(6) + "_" + fname;
                fileDto.setOriginalName(realName);
                fileDto.setNewFileName(fname);
                fname = upath + fname;
                //保存文件到服务器本地指定路径
                boolean b = FileUtil.SaveFileByPhysicalDir(realPath, fname, mf.getInputStream());
                fileDto.setSourceUrl(realPath + fname);
                //如果是图片，则获取该图片的高宽以及做一些压缩处理
                if (b && mf.getContentType().indexOf("image") != -1) {
                    BufferedImage img = ImageIO.read(mf.getInputStream());
                    int width = img.getWidth();
                    int height = img.getHeight();
                    System.out.println("width:" + width + ",height:" + height);
                    fileDto.setImgWidth(width);
                    fileDto.setImgHeight(height);
                    if (width >= 1920 && height >= 1080) {
                        minLogoUrl = realPath + fname.substring(0, fname.lastIndexOf(".")) + "MinLogo." + ext;
                        System.out.println("resultUrl:" + minLogoUrl);
                        //图片按照给定的宽度和高度裁剪压缩
                        ImageUtil.scale(realPath + fname, minLogoUrl, width / 2, 1080 / 2, false);
                        fileDto.setMinLogoUrl(minLogoUrl);
                    }
                }

                fileDtoList.add(fileDto);
            }
            return fileDtoList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileDtoList;
    }

    @Override
    public List<UnitFile> uploadFilesToServer(List<FileDto> fileDtos, String realPath,
                                              String userId, String userType, String resId, String resType, String opeType) {
        String upath = ConfigUtil.getStringValue("smbdp.tempPath");
        List<UnitFile> unitFileList = new ArrayList<UnitFile>();
        try {
            String ext;
            UnitFile unitFile = null;
            for (FileDto fileDto : fileDtos
                    ) {
                String fname = fileDto.getNewFileName();
                if (fname.lastIndexOf(".") > 0) {
                    ext = fname.substring(fname.lastIndexOf(".") + 1, fname.length());
                } else {
                    ext = "";
                }
                File sourceFile = null;
                File minLogoFile = null;
                File middleLogoFile = null;
                File maxLogoFile = null;
                unitFile = new UnitFile();
                unitFile.setExt(ext);
                unitFile.setDescript(fileDto.getDescript());
                unitFile.setTitle(fileDto.getOriginalName());
                unitFile.setUserId(userId);
                unitFile.setResId(resId);
                unitFile.setResType(resType);
                unitFile.setUserType(userType);
                unitFile.setOpeType(opeType);
                unitFile.setCreateTime(new Date());
                unitFile.setModifyTime(new Date());
                //如果是图片则存储图片的高宽
                if (fileDto.getImgHeight() != null && fileDto.getImgHeight() > 0) {
                    unitFile.setHeight(fileDto.getImgHeight());
                }

                if (fileDto.getImgWidth() != null && fileDto.getImgWidth() > 0) {
                    unitFile.setWidth(fileDto.getImgWidth());
                }

                //上传图片源文件,上传后删除源文件
                if (fileDto.getSourceUrl() != null && !"".equals(fileDto.getSourceUrl())) {
                    String path = FastDFSService.uploadFile(fileDto.getSourceUrl(), ext);
                    unitFile.setSourceUrl(path);
                    sourceFile = new File(fileDto.getSourceUrl());
                    if (sourceFile.exists()) {
                        sourceFile.delete();
                    }
                }
                //上传小图LOGO
                if (fileDto.getMinLogoUrl() != null && !"".equals(fileDto.getMinLogoUrl())) {
                    String path = FastDFSService.uploadFile(fileDto.getMinLogoUrl(), ext);
                    unitFile.setMinLogoUrl(path);
                    minLogoFile = new File(fileDto.getMinLogoUrl());
                    if (minLogoFile.exists()) {
                        minLogoFile.delete();
                    }
                }
                //上传中图LOGO
                if (fileDto.getMiddleLogoUrl() != null && !"".equals(fileDto.getMiddleLogoUrl())) {
                    String path = FastDFSService.uploadFile(fileDto.getMiddleLogoUrl(), ext);
                    unitFile.setMiddleLogoUrl(path);
                    middleLogoFile = new File(fileDto.getMiddleLogoUrl());
                    if (middleLogoFile.exists()) {
                        middleLogoFile.delete();
                    }
                }
                //上传大图片LOGO
                if (fileDto.getMaxLogoUrl() != null && !"".equals(fileDto.getMaxLogoUrl())) {
                    String path = FastDFSService.uploadFile(fileDto.getMaxLogoUrl(), ext);
                    unitFile.setMaxLogoUrl(path);
                    maxLogoFile = new File(fileDto.getMaxLogoUrl());
                    if (maxLogoFile.exists()) {
                        maxLogoFile.delete();
                    }
                }
                this.insertObject_common(unitFile);
                unitFileList.add(unitFile);
            }
            return unitFileList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitFileList;
    }

    public boolean deleteFiles(String[] sysFileIds, String userId) {
        if (sysFileIds == null) {
            return false;
        }
        UnitFile sf = null;
        for (String id : sysFileIds
                ) {
            sf = this.selectById_common(id);
            if (sf == null) {
                return false;
            }
            // TODO 如果文件不属于当前用户则不可以进行删除
//            if(!sf.getUserId().equals(TokenUtil.getUserId())){
//                return false;
//            }
            if (sf.getSourceUrl() != null && !"".equals(sf.getSourceUrl())) {
                int a = FastDFSService.deleteFile(sf.getSourceUrl());
                System.out.println("a:" + a);
            }

            if (sf.getMaxLogoUrl() != null && !"".equals(sf.getMaxLogoUrl())) {
                FastDFSService.deleteFile(sf.getMaxLogoUrl());
            }

            if (sf.getMiddleLogoUrl() != null && !"".equals(sf.getMiddleLogoUrl())) {
                FastDFSService.deleteFile(sf.getMiddleLogoUrl());
            }
            if (sf.getMinLogoUrl() != null && !"".equals(sf.getMinLogoUrl())) {
                FastDFSService.deleteFile(sf.getMinLogoUrl());
            }

            unitFileDao.deleteById_common(id);
        }
        return true;
    }

    @Override
    public boolean deleteFile(String unitFileId, String userId) {
        if (unitFileId == null || "".equals(unitFileId)) {
            return false;
        }
        UnitFile sf = null;
        sf = this.selectById_common(unitFileId);
        if (sf == null) {
            return false;
        }
        // TODO 如果文件不属于当前用户则不可以进行删除
//        if (!sf.getUserId().equals(TokenUtil.getUserId())) {
//            return false;
//        }
        if (sf.getSourceUrl() != null && !"".equals(sf.getSourceUrl())) {
            int a = FastDFSService.deleteFile(sf.getSourceUrl());
        }

        if (sf.getMaxLogoUrl() != null && !"".equals(sf.getMaxLogoUrl())) {
            FastDFSService.deleteFile(sf.getMaxLogoUrl());
        }

        if (sf.getMiddleLogoUrl() != null && !"".equals(sf.getMiddleLogoUrl())) {
            FastDFSService.deleteFile(sf.getMiddleLogoUrl());
        }
        if (sf.getMinLogoUrl() != null && !"".equals(sf.getMinLogoUrl())) {
            FastDFSService.deleteFile(sf.getMinLogoUrl());
        }
        unitFileDao.deleteById_common(unitFileId);
        return true;
    }

    @Override
    public List<UnitFile> getList(UnitFile unitFile) {
        return unitFileDao.selectList(unitFile);
    }


    @Override
    public List<UnitFile> uploadFiles(String fileJson, String realPath, String resId, String resType, String opeType, String userId) {
        //非空判断
        if(fileJson ==null || "".equals(fileJson) ){
            return null;
        }
        if(realPath == null || "".equals(realPath)){
            return null;
        }
        if(userId == null || "".equals(userId)){
            return null;
        }
        //对json字符串进行转码处理
        String jsonStr = StringEscapeUtils.unescapeHtml4(fileJson);
        //转为json数组
        JSONArray jarray = new JSONArray(jsonStr);
        List<FileDto> fileDtoList = new ArrayList<FileDto>();
        FileDto fileDto = null;
        List<UnitFile> files = null;
        if (jarray != null){
            //循环每一张图片并添加到集合中
            for (int i = 0; i < jarray.size(); i++) {
                JSONObject jobj = jarray.getJSONObject(i);
                fileDto = new FileDto(jobj);
                fileDtoList.add(fileDto);
            }

            if (!fileDtoList.isEmpty()) {
                //上传文件到文件服务器
                files = this.uploadFilesToServer(fileDtoList, realPath, userId,
                        null, resId, resType, opeType);
            }
        }
        return files;
    }
}
